package com.v1.video.db.service;

import java.util.ArrayList;
import java.util.List;

import com.v1.video.AppContext;
import com.v1.video.db.dao.StatisticsTB;
import com.v1.video.db.dao.StatisticsTBDao;
import com.v1.video.dbcore.greenrobot.dao.query.QueryBuilder;
import com.v1.video.domain.Channel;

public class StatisticsDB {
	
	private static StatisticsDB mInstance;
	private StatisticsTBDao mStatisticsTBDao;

	private StatisticsDB() {
		mStatisticsTBDao = AppContext.getDaoSession().getStatisticsTBDao();
	}

	public static StatisticsDB getInstance() {
		if (mInstance == null) {
			mInstance = new StatisticsDB();
		}
		return mInstance;
	}
	
	public void insert(StatisticsTB entity) {
		mStatisticsTBDao.insert(entity);
	}
	
	
	public void update(StatisticsTB entity) {
		mStatisticsTBDao.update(entity);
	}
	
	public void insertOrUpdate(String cid) {
		List<StatisticsTB> lst = queryData(cid);
		if (lst != null && lst.size() > 0) {
			StatisticsTB statistic = lst.get(0);
			statistic.setCount(statistic.getCount() + 1);
			update(statistic);
		} else {
			StatisticsTB statistic = new StatisticsTB();
			statistic.setCid(cid);
			statistic.setCount(1);
			insert(statistic);
		}
	}
	
	public void insertInTx(List<Channel> entities) {
		if (entities != null && entities.size() > 0) {
			List<StatisticsTB> mLst = new ArrayList<StatisticsTB>();
			for (int i = 0; i < entities.size(); i++) {
				StatisticsTB statistic = new StatisticsTB();
				statistic.setCid(entities.get(i).getCid());
				statistic.setCount(0);
				mLst.add(statistic);
			}
			if (mLst.size() > 0) {
				try {
					mStatisticsTBDao.insertInTx(mLst);
				} catch (Exception e) {

				}
			}
		}
	}
	
	private List<StatisticsTB> queryData(String cid) {
		QueryBuilder<StatisticsTB> query = mStatisticsTBDao.queryBuilder()
				.where(StatisticsTBDao.Properties.Cid.eq(cid));
		return query.build().list();
	}
	
	public List<StatisticsTB> queryData() {
		QueryBuilder<StatisticsTB> query = mStatisticsTBDao.queryBuilder()
				.where(StatisticsTBDao.Properties.Cid.notEq("0"))
				.orderDesc(StatisticsTBDao.Properties.Count).offset(0).limit(4);
		return query.build().list();
	}
	
}
